/**
 * Project Name:mbr-ws-web
 * File Name:SHAEncoder.java
 * Package Name:com.aeye.mbr.ws.util
 * Date:2016年1月6日下午4:57:47
 * Copyright (c) 2016, shengpeng@a-eye.cn All Rights Reserved.
 *
 */

package com.aeye.mbr.ws.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * ClassName:SHAEncoder <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016年1月6日 下午4:57:47 <br/>
 * 
 * @author shengpeng
 * @version
 * @since JDK 1.6
 * @see
 */
public class SHAEncoder {
	public static String Encrypt(String strSrc) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance("SHA-1");
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			//System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}
	public static String Encrypt(String strSrc, String encName) {
		// parameter strSrc is a string will be encrypted,
		// parameter encName is the algorithm name will be used.
		// encName dafault to "MD5"
		MessageDigest md = null;
		String strDes = null;

		byte[] bt = strSrc.getBytes();
		try {
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
		} catch (NoSuchAlgorithmException e) {
			//System.out.println("Invalid algorithm.");
			return null;
		}
		return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
	
	public static void mainTest(String[]args) {
		SHAEncoder te=new SHAEncoder();
		String strSrc="可以加密汉字.Oh,and english";
		//System.out.println("Source String:"+strSrc);
		//System.out.println("Encrypted String:");
		//System.out.println("Use Def:"+te.Encrypt(strSrc));
		//System.out.println("Use MD5:"+te.Encrypt(strSrc,"MD5"));
		//System.out.println("Use SHA:"+te.Encrypt(strSrc,"SHA-1"));
		//System.out.println("Use SHA-256:"+te.Encrypt(strSrc,"SHA-256"));
	}
}
